package com.sishu.njrtsdms.config.redis;

import cn.hutool.extra.spring.SpringUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * Redis使用FastJson序列化
 */
public class ObjectMapper2JsonRedisSerializer<T> implements RedisSerializer<T> {
    public static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;

    private final Class<T> clazz;

    private final ObjectMapper objectMapper = SpringUtil.getBean(ObjectMapper.class);


    public ObjectMapper2JsonRedisSerializer(Class<T> clazz) {
        super();
        this.clazz = clazz;
    }

    @SneakyThrows
    @Override
    public byte[] serialize(T t) throws SerializationException {
        if (t == null) {
            return new byte[0];
        }
        return objectMapper.writeValueAsString(t).getBytes(DEFAULT_CHARSET);
    }

    @Override
    @SneakyThrows
    public T deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        String str = new String(bytes, DEFAULT_CHARSET);
        return objectMapper.readValue(str, clazz);
    }
}
